
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import xyz.erupt.core.annotation.EruptDataSource

import java.io.*
/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.example.demo.model.mnt;"
typeMapping = [
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)datetime|timestamp/)       : "java.util.Date",
        (~/(?i)date/)                     : "java.util.Date",
        (~/(?i)time/)                     : "java.util.Date",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def tableNameDispose = table.getName().substring((table.getName().indexOf("dr_") + 2), table.getName().length())
    out.println tableNameDispose
    def className = javaName(tableNameDispose, true)
    out.println className
    def fields = calcFields(table)
    PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + ".java")), "utf-8"))
    output.withPrintWriter { out -> generate(out, className, fields,table.getName()) }
}

def generate(out, className, fields,tableName) {
    out.println "package $packageName"


    out.println "import xyz.erupt.annotation.Erupt;"
    out.println "import xyz.erupt.annotation.EruptField;"
    out.println "import xyz.erupt.annotation.sub_erupt.Power;"
    out.println "import xyz.erupt.annotation.sub_field.Edit;"
    out.println "import xyz.erupt.annotation.sub_field.EditType;"
    out.println "import xyz.erupt.annotation.sub_field.View;"
    out.println "import xyz.erupt.annotation.sub_field.ViewType;"
    out.println "import xyz.erupt.annotation.sub_field.sub_edit.*;"
    out.println "import xyz.erupt.jpa.model.BaseModel;"
    out.println ""
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Lob;"
    out.println "import javax.persistence.Table;"
    out.println ""
    out.println "@EruptDataSource(\"数据源\")"
    out.println "@Erupt(name = \"${tableName}\")"
    out.println "@Entity"
    out.println "@Table(name = \"${tableName}\")"
    out.println "public class $className extends BaseModel {"
    out.println ""
//    def msum= (long)(Math.random()*1000000000000000000+1000000000000000000)
//    out.println  "  private static final long serialVersionUID = ${msum}L;"
    fields.each() {
        if (isNotEmpty(it.commoent)) {
            out.println ""

            out.println "\t/**"
            out.println "\t * ${it.commoent}"
            out.println "\t */"
        }
        if (it.annos != "") out.println "  ${it.annos}"

        out.println "  @EruptField("
        out.println "          views = @View("
        out.println "                  title = \"${it.commoent}\", sortable = true"
        out.println "          ),"
        out.println "          edit = @Edit("
        out.println "                  title = \"${it.commoent}\","
        out.println "                  type = EditType.INPUT, search = @Search, notNull = true,"
        out.println "                  inputType = @InputType"
        out.println "          )"
        out.println "  )"
        out.println "  private ${it.type} ${it.name};"
    }
    out.println ""
    fields.each() {
        out.println ""
        out.println "  public ${it.type} get${it.name.capitalize()}() {"
        out.println "    return ${it.name};"
        out.println "  }"
        out.println ""
        out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
        out.println "    this.${it.name} = ${it.name};"
        out.println "  }"
        out.println ""
    }
    out.println "}"
}

def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           commoent: col.getComment(),
                           annos: ""]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
def isNotEmpty(content) {
    return content != null && content.toString().trim().length() > 0
}


